<?php
declare(strict_types=1);

namespace Zms\HyperfResponse;

use Hyperf\Context\Context;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Zms\Exception\ExceptionCode;
use Zms\Unit\Json;
use Zms\Res\Result as BusResult;

class Api
{

    /**
     * 成功响应
     * @param string $msg
     * @param mixed|null $data
     * @param mixed|null $debug
     * @return ResponseInterface
     */
    public function success(string $msg = '请求成功', mixed $data = null, mixed $debug = null): ResponseInterface
    {
        return $this->data(ExceptionCode::SUCCESS, $msg, $data, $debug);
    }


    /**
     * 响应失败数据
     * @param string $msg
     * @param mixed|null $data
     * @param mixed|null $debug
     * @return ResponseInterface
     */
    public function fail(string $msg = '请求失败', mixed $data = null, mixed $debug = null): ResponseInterface
    {
        return $this->data(ExceptionCode::MSG_FAIL, $msg, $data, $debug);
    }


    /**
     * 响应错误数据
     * @param string $msg
     * @param mixed|null $data
     * @param mixed|null $debug
     * @return ResponseInterface
     */
    public function error(string $msg = '系统错误', mixed $data = null, mixed $debug = null): ResponseInterface
    {
        return $this->data(ExceptionCode::ERROR, $msg, $data, $debug);
    }


    /**
     * 数据响应
     * @param int $code
     * @param string $msg
     * @param mixed|null $data
     * @param mixed|null $debug
     * @return ResponseInterface
     */
    public function data(int $code, string $msg, mixed $data = null, mixed $debug = null): ResponseInterface
    {
        if (is_null($data)) {
            $result = ['code' => $code, 'msg' => $msg, 'data' => null];
        } else {
            $result = ['code' => $code, 'msg' => $msg, 'data' => Result::toResponse($data)];
        }
        return $this->json($result);
    }


    /**
     * 响应JSON
     * @param array $data
     * @return ResponseInterface
     */
    public function json(array $data): ResponseInterface
    {
        /**
         * @var ResponseInterface $response
         */
        $response = Context::get(ResponseInterface::class);
        return $response->withStatus(200)->withHeader('Content-Type', 'application/json; charset=utf-8')->withBody(new SwooleStream(Json::encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)));
    }


    /**
     * @describe 结果集响应
     * @user zlf <zms-pro@qq.com> 2025/8/6
     * @param BusResult $result
     * @return ResponseInterface
     */
    public function result(BusResult $result): ResponseInterface
    {
        if ($result->getState()) {
            return $this->success($result->getMessage(), $result->getData());
        }
        return $this->fail($result->getMessage(), $result->getData());
    }
}